package com.atguigu.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程交替运行
 */
public class TestABCAlternate2{

    public static void main(String[] args) {
        AlternateDemo2 alternateDemo = new AlternateDemo2();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 10; i++) {
                    alternateDemo.loopA(i);
                }
            }
        },"A").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 10; i++)  {
                    alternateDemo.loopB(i);
                }
            }
        },"B").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 10; i++) {
                    alternateDemo.loopC(i);
                }
            }
        },"C").start();
    }
}


class AlternateDemo2 {

    private int number = 1;
    private ReentrantLock lock = new ReentrantLock();
    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();
    private Condition conditionC = lock.newCondition();


    public void loopA(int totalLoop){
        lock.lock();
        try {
            //判断
            if (number != 1) {
                conditionA.await();
            }

            // 打印
            for (int i = 0; i < 1; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" +  i + "\t" + totalLoop);
            }

            // 唤醒
            number = 2;
            conditionB.signal();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void loopB(int totalLoop){
        lock.lock();
        try {
            if (number != 2) {
                conditionB.await();
            }

            for (int i = 0; i < 2; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" +  i + "\t" + totalLoop);
            }

            number = 3;
            conditionC.signal();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void loopC(int totalLoop){
        lock.lock();
        try {
            if (number != 3) {
                conditionC.await();
            }

            for (int i = 0; i < 3; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" +  i + "\t" + totalLoop);
            }
            System.out.println("-------------------------------");

            number = 1;
            conditionA.signal();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
